﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using Zzva.Common;
using Zzva.DomainObjectReg;
using Zzva.DomainObject;
using System.Reflection;
using System.Collections;

namespace Zzva.UIWin
{
    public partial class TFrmRegDirBase : Form
    {


        protected int mvarFlgColumnIndexCur;
        //объявляем  объект делегата
        public event EventHandler EventReady;
        protected bool mvarFlgStateLoadForm; //состояние загрузки формы
        //protected TRegDirBase mvarRegDirBase; 



        //Возвращает алиса текущего поля
        ////private string GetCurColumnObozn()
        protected string GetCurColumnObozn()

        {
            try
            {
                DataGridViewCell lCurCell;
                DataGridViewColumn lCurColumn;
                string lCurColumnAlias;
                ////string lCurColumnObozn;

                lCurCell = dgvMain.CurrentCell;
                if (lCurCell != null)
                {
                    lCurColumn = dgvMain.Columns[lCurCell.ColumnIndex];
                    lCurColumnAlias = lCurColumn.Name;
                    ////lCurColumnObozn = lCurColumnAlias;
                }
                else //нет текущей ячейки
                {
                    ////lCurColumnObozn = "";
                    lCurColumnAlias = "";
                } 

                ////return lCurColumnObozn;
                return lCurColumnAlias;
            }
            catch (Exception e1) { throw e1; }
            finally { }
        }


























































































































































        protected void RegDirBase_FindDir(object lSender, EventArgs lEventArgs)
        {
            {
                try
                {
                    bool lResult;
                    TDirBase lCurDir;
                    int lCurIndex;

                    TDirFindEventArgs lDirFindEventArgs = (TDirFindEventArgs)lEventArgs;

                    lResult = lDirFindEventArgs.Result;
                    lCurDir = lDirFindEventArgs.CurDir;

                    if (lResult == false)
                    {
                        ////throw (new CommonException("Ничего не найдено"));
                    }
                    else
                    {
                        lCurIndex = GetIndexForId(dgvMain.Rows, lCurDir.Id);
                        if (lCurIndex == -1) { throw (new CommonException("Текущая запись не найдена")); }
                        dgvMain.CurrentCell = dgvMain.Rows[lCurIndex].Cells[mvarFlgColumnIndexCur];
                    }
                }
                catch (Exception e1) { throw e1; }
                finally { }
            }
        }























































































        //Возвращает список полей для источника
        protected Collection<string> GetListAliasField()
        {
            try
            {
                object lDataSourse = dgvMain.DataSource;
                IList lListDataSource;

                if (lDataSourse == null) {throw (new CommonException("Нет данных"));}

                if (lDataSourse is IList){lListDataSource = (IList)lDataSourse;}
                else { throw (new CommonException("В источнике данных содержится не Ilist")); }


                if (lListDataSource.Count <= 0) { throw (new CommonException("Нет записей")); }


                object lItem;
                lItem = lListDataSource[0];

                Type lTypeItem;
                PropertyInfo[] myPropertyInfo;

                lTypeItem = lItem.GetType();

                myPropertyInfo = lTypeItem.GetProperties();

                Collection<string> lListAliasField  = new Collection<string>(); 

                for (int i = 0; i < myPropertyInfo.Length; i++)
                {
                    lListAliasField.Add(myPropertyInfo[i].Name);
                }


                return lListAliasField;

            }
            catch (Exception e1) { throw e1; }
            finally { }
        }



        protected  void FrmFilterByValue_Ready(object Sender, EventArgs ArgsBase)
        {
            try
            {
                string lAlias;
                string lFilterValue;

                if (ArgsBase is TListFieldValueEventArgs)
                {
                    TFieldValue lFieldValue; 

                    TListFieldValueEventArgs lListFieldValueEventArgs = (TListFieldValueEventArgs)ArgsBase;
                    Collection<TFieldValue> lListFieldValue = lListFieldValueEventArgs.ListFieldValue;

                    if (lListFieldValue.Count != 2) { throw (new CommonException("Не соответсвует число параметров")); }

                    lFieldValue = lListFieldValue.SingleOrDefault(h => h.Field == "Alias");
                    if (lFieldValue == null) { throw (new CommonException("Отсутсвует параметр Alias")); }
                    lAlias = (string)lFieldValue.Value;

                    lFieldValue = lListFieldValue.SingleOrDefault(h => h.Field == "FilterValue");
                    if (lFieldValue == null) { throw (new CommonException("Отсутсвует параметр FilterValue")); }
                    lFilterValue = (string)lFieldValue.Value;
                }
                else { throw (new CommonException("Не те аргументы в ответе")); }

                AddFilterForColumn(lFilterValue, lAlias); 

            }

            catch (Exception e1) { throw e1; }
            finally { }
        }


        private void cmdFilterByValue_Click(object sender, EventArgs e)
        {
            FilterByValue();
        }

        protected virtual void FilterByValue()
        {
            try
            {
                ////TFrmFilterByValue FrmFilterByValue;
                ////FrmFilterByValue = new TFrmFilterByValue();
                ////FrmFilterByValue.EventReady += new EventHandler(FrmFilterByValue_Ready);
                ////FrmFilterByValue.ShowDialog();

                throw (new CommonException("Метод не реализован")); 


            }

            catch (Exception e1) { throw e1; }
            finally { }
        }


 



        ////private string GetCurSelectValue()
        ////{
        ////    try
        ////    {
        ////        string lSelectValue;
        ////        lSelectValue = txtFilter.Text;
        ////        return lSelectValue;
        ////    }
        ////    catch (Exception e1) { throw e1; }
        ////    finally { }
        ////}



        private void FilterReadAndAdd()
        {
            try
            {
                ////TFilterValue lFilteValue;
                string lCurColumnObozn;
                string lFilterTemplate;

                lCurColumnObozn = GetCurColumnObozn();

                ////lFilterTemplate = GetCurSelectValue().Trim();
                lFilterTemplate = txtFilter.Text;

                ////if (lCurColumnObozn != "")//просто нажал кнопку без выделения столбца, игнорируем...
                ////{
                ////    if (lFilterTemplate != "")
                ////    {
                ////        lFilteValue = new TFilterValue(lCurColumnObozn, lFilterTemplate);
                ////        FilterAdd(lFilteValue);
                ////    }
                ////}
                AddFilterForColumn(lFilterTemplate, lCurColumnObozn);

            }
            catch (Exception e) { MessageBox.Show(e.Message); }
            finally { }
        }



        //Добавить фильтр для заданного столбца
        private void AddFilterForColumn(string pFilterTemplate, string pColumnObozn)
        {
            try
            {
                TFilterValue lFilteValue;
                if (pColumnObozn != "")//просто нажал кнопку без выделения столбца, игнорируем...
                {
                    if (pFilterTemplate.Trim()  != "")
                    {
                        lFilteValue = new TFilterValue(pColumnObozn, pFilterTemplate.Trim());
                        FilterAdd(lFilteValue);
                    }
                }
            }
            catch (Exception e) { throw e;}
            finally { }
        }

        private void cmdFilterBySelection_Click(object sender, EventArgs e)
        {
            FilterBySelection();
        }

        private void FilterBySelection()
        {
            try
            {
                DataGridViewTextBoxEditingControl lTextBox;
                DataGridViewCell lCurCell;
                System.Windows.Forms.Control lCurCellControl;
                string lSelectText;
                object lCurCellValue;
                int lCurRowIndex;
                DataGridViewRow lCurRow;
                int lCurColumnIndex;
                DataGridViewColumn lCurColumn;
                string lCurColumnAlias;

                lCurCell = dgvMain.CurrentCell;
                if (lCurCell == null) { throw (new CommonException("Выделите ячейку")); }

                lCurRowIndex = lCurCell.RowIndex;
                if (lCurRowIndex < 0) { throw (new CommonException("Выделите строку со значениями")); }
                lCurRow = dgvMain.Rows[lCurRowIndex];


                lCurColumnIndex = lCurCell.ColumnIndex;
                if (lCurColumnIndex < 0) { throw (new CommonException("Выделите столбец со значениями")); }
                if (lCurColumnIndex == 0) { throw (new CommonException("Выделите текст предметной ячейки")); }
                lCurColumn = dgvMain.Columns[lCurColumnIndex];  


                //здесь не должен быть зрительно выделена вся строка
                if (lCurRow.Selected == true) { throw (new CommonException("Выделите текст в конкретной ячейке")); }
                

                Type lType;
                lType = lCurCell.EditType; // только в контроле есть текст (я так думаю)
                if (lType.Name != "DataGridViewTextBoxEditingControl") { throw (new CommonException("Это не DataGridViewTextBoxEditingControl")); }
             

                lCurCellControl = dgvMain.EditingControl;//спрашиваем состояние режима редактрования конторла
                if (lCurCellControl == null)//находимся не врежиме редактирования, считываем полное значение
                {
                    lCurCellValue = lCurCell.Value; // это объект в ячейке
                    lSelectText = lCurCellValue.ToString(); //а это его строковое представление
                }
                else
                {
                    lTextBox = (DataGridViewTextBoxEditingControl)lCurCellControl;
                    lSelectText = lTextBox.SelectedText;
                }


                //lSelectText = lSelectText.Trim();
 
                //Имя столбца
                lCurColumnAlias = lCurColumn.Name;

                AddFilterForColumn(lSelectText, lCurColumnAlias); 

            }
            catch (Exception e1){MessageBox.Show(e1.Message); }
            finally { }
        }

        private void dgvMain_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            MakeEditCell(e.RowIndex, e.ColumnIndex);
        }

        private void dgvMain_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //MakeEditCell(e.RowIndex,e.ColumnIndex);
        }

        private void MakeEditCell(int pCellRow, int pCellColumn)
        {
            try
            {

                if (pCellRow >= 0 & pCellColumn >= 0)
                {
                    DataGridViewCell lCell;
                    lCell = dgvMain.Rows[pCellRow].Cells[pCellColumn];
                    lCell.ReadOnly = false;
                }
            }

            catch (Exception e1) { MessageBox.Show(e1.Message); }
            finally { }
        }

        private void dgvMain_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            MakeNotEditCell(e.RowIndex, e.ColumnIndex);
        }

        private void MakeNotEditCell(int pCellRow, int pCellColumn)
        {
            try
            {
                DataGridViewCell lCell;
                lCell = dgvMain.Rows[pCellRow].Cells[pCellColumn];
                lCell.ReadOnly = true;
            }
            catch (Exception e1) { MessageBox.Show(e1.Message); }
            finally { }
        }































































        #region Report...

        private void cmdReport_Click(object sender, EventArgs e)
        {
            Report(); 
        }

        protected virtual void Report()
        { throw (new CommonException("Метод не реализован")); }

        #endregion





        protected virtual void FrmDirBase_Ready(object Sender, EventArgs ArgsBase)
        { throw (new CommonException("Метод не реализован")); }



        ////protected virtual  void AddDir(TDirITCompanyNew pDir)
        ////{ throw (new CommonException("Метод не реализован")); }





        #region Find...


        //Установить курсор на заданном объекте
        public virtual void FindByDir(TDirBase pDir)
        { throw (new CommonException("Метод не реализован")); }


        protected virtual void FindPrev(TFilterValue pFindValue)
        { throw (new CommonException("Метод не реализован")); }


        protected virtual void FindNext(TFilterValue pFindValue)
        { throw (new CommonException("Метод не реализован")); }



        protected virtual void Find(TFilterValue pFindValue)
        { throw (new CommonException("Метод не реализован")); }






        #endregion



        #region Constructor...

        public TFrmRegDirBase()
        {
            mvarFlgStateLoadForm = true;

            InitializeComponent();


        }

        #endregion







        protected void RegDirBase_UpdateList(object lSender, EventArgs lEventArgs)
        {
            {
                try{ViewCurrentList();}
                catch (Exception e1) { throw e1; }
                finally { }
            }
        }



        protected virtual void ViewCurrentList()
        { throw (new CommonException("Метод не реализован")); }




        //Возвратить индекс строки  ДатаГрид по ИД  
        protected int GetIndexForId(DataGridViewRowCollection lGridViewRowCollection, int pId)
        {
            try
            {
                int lIndex;
                lIndex = -1;

                foreach (DataGridViewRow dr in lGridViewRowCollection)
                {
                    if ((int)(dr.Cells["Id"].Value) == pId)
                    {
                        lIndex = dr.Index;
                        break;
                    }
                }

                return lIndex;
            }

            catch (Exception e1) { throw e1; }
            finally { }
        }



























        #region Find...


        #region FindPrev...

        private void cmdFindPrev_Click(object sender, EventArgs e)
        {
            FindPrevReadAndSearch();
        }

        private void FindPrevReadAndSearch()
        {
            try
            {
                TFilterValue lFindValue;

                lFindValue = GetFindValue();
                if (lFindValue == null) { throw (new CommonException("Не возможно определить критерии поиска")); }
                FindPrev(lFindValue);
            }

            catch (Exception e1) { MessageBox.Show(e1.Message); }
            finally { }
        }

////        protected virtual void FindPrev(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); }

        #endregion



        #region FindNext...

        private void cmdFindNext_Click(object sender, EventArgs e)
        {
            FindNextReadAndSearch();
        }

        private void FindNextReadAndSearch()
        {
            try
            {
                TFilterValue lFindValue;

                lFindValue = GetFindValue();
                if (lFindValue == null) { throw (new CommonException("Не возможно определить критерии поиска")); }
                FindNext(lFindValue);
            }

            catch (Exception e1) { MessageBox.Show(e1.Message); }
            finally { }
        }

////       protected virtual void FindNext(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); }

        #endregion




        #region FindWith0...

        private void cmdFind_Click(object sender, EventArgs e)
        {
            FindReadAndSearch();
        }

        private void FindReadAndSearch()
        {
            try
            {
                TFilterValue lFindValue;

                lFindValue = GetFindValue();
                if (lFindValue == null) { throw (new CommonException("Не возможно определить критерии поиска")); }
                Find(lFindValue);
            }

            catch (Exception e1){MessageBox.Show(e1.Message);}
            finally { }
        }

////        protected virtual void Find(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); }
        
        #endregion



        //Возвращает критерий поиска
        //Возвращает null, если
        //1.критерий поиска пустая строка
        //2.не возможно определить поле по которому искать
        private TFilterValue GetFindValue()
        {
            try
            {
                string lCurColumnObozn;
                TFilterValue lFindValue;
                string lFindTemplate;

                lFindValue = null;

                lCurColumnObozn = GetCurColumnObozn();

                if (lCurColumnObozn != "")
                {
                    lFindTemplate = txtFind.Text.Trim();
                    if (lFindTemplate != "") { lFindValue = new TFilterValue(lCurColumnObozn, lFindTemplate); }
                    else { lFindValue = null; }
                }
                else { lFindValue = null; }

                return lFindValue;
            }

            catch (Exception e1) { throw e1; }
            finally { }
        }



        #endregion


 





















        private void dgvMain_CellEnter(object sender, DataGridViewCellEventArgs e)
        {

            if (mvarFlgStateLoadForm == false)
            { mvarFlgColumnIndexCur = dgvMain.CurrentCell.ColumnIndex; }
 
        }



        #region Filter...


        private void cmdFilterAdd_Click(object sender, EventArgs e)
        {

            FilterReadAndAdd();

        }






  
 





        protected virtual void FilterAdd(TFilterValue pFilterValue) { throw (new CommonException("Метод не реализован")); }


        private void cmdFilterDel_Click(object sender, EventArgs e)
        {
            FilterDel();
        }

        protected virtual void FilterDel() { throw (new CommonException("Метод не реализован")); }


        #endregion




        #region Sort...

        private void cmdSortasc_Click(object sender, EventArgs e)
        {
            SortAcs();
        }

        private void cmdSortdes_Click(object sender, EventArgs e)
        {
            SortDes();
        }

        private void SortDes()
        {
            try
            {
                TSortValue lSortValue;
                string lCurColumnObozn;

                lCurColumnObozn = GetCurColumnObozn();
                if (lCurColumnObozn != "")
                {
                    lSortValue = new TSortValue(lCurColumnObozn, ESortType.OrderBackward);
                    Sort(lSortValue);  
                }
            }

            catch (Exception e) { MessageBox.Show(e.Message); }
            finally { }
        }

        private void SortAcs()
        {
            try
            {
                TSortValue lSortValue;
                string lCurColumnObozn;

                lCurColumnObozn = GetCurColumnObozn();
                if (lCurColumnObozn != "")
                {
                    lSortValue = new TSortValue(lCurColumnObozn, ESortType.OrderForward);
                    Sort(lSortValue); 
                }  
            }

            catch (Exception e){MessageBox.Show(e.Message);}
            finally { }
        }

        protected virtual void Sort(TSortValue pSortValue) { throw (new CommonException("Метод не реализован")); }

        #endregion









        #region OboznAndAlias...


////        private  string GetColumnOboznByAlias(string pAlias)
////        {
////            try
////            {
////                TOboznAndAlias lOboznAndAlias;
////                string lObozn;
////                Collection<TOboznAndAlias> lListOboznAndAlias = GetListOboznAndAlias();
////                lOboznAndAlias = lListOboznAndAlias.FirstOrDefault(d => d.Alias == pAlias);
////                if (lOboznAndAlias != null){lObozn = lOboznAndAlias.Obozn;}
////                else{lObozn = "";}
////                return lObozn;
////            }
////
////            catch (Exception e1) { throw e1; }
////            finally { }
////        }



////        protected virtual Collection<TOboznAndAlias> GetListOboznAndAlias()
////        {
////            Collection<TOboznAndAlias> lList;
////            lList = new Collection<TOboznAndAlias>();
////            lList.Add(new TOboznAndAlias("Id","Id"));
////            lList.Add(new TOboznAndAlias("Obozn", "Обозначение"));
////            lList.Add(new TOboznAndAlias("Naim", "Наименование"));
////            return lList;
////        }



////        private string GetColumnAliasByObozn(string pObozn)
////        {
////            try
////            {
////                TOboznAndAlias lOboznAndAlias;
////                string lAlias;
////                Collection<TOboznAndAlias> lListOboznAndAlias = GetListOboznAndAlias();
////                lOboznAndAlias = lListOboznAndAlias.FirstOrDefault(d => d.Obozn  == pObozn);
////                if (lOboznAndAlias != null) { lAlias = lOboznAndAlias.Alias; }
////                else { lAlias = ""; }
////                return lAlias;
////            }
////            catch (Exception e1) { throw e1; }
////            finally { }
////        }



        #endregion








        #region Delete...

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            DeleteWithDialUser();
        }


        private void DeleteWithDialUser()
        {
            try
            {
                string caption = "Удаление!";
                string message = "Удалить текущую запись?";
                MessageBoxButtons buttons = MessageBoxButtons.OKCancel;
                DialogResult result = MessageBox.Show(message, caption, buttons);

                switch (result)
                  {
                     case DialogResult.OK:
                        Delete();
                        break;
                     case DialogResult.Cancel:
                        break;
                     default: throw (new CommonException("Нет ответа диалога"));
                  }
            }
            catch (Exception e) { MessageBox.Show(e.Message); }
            finally { }
        }


        protected virtual void Delete(){throw (new CommonException("Метод не реализован")); }

        #endregion




        #region Edit...

        private void cmdEdit_Click(object sender, EventArgs e)
        {
            Edit();
        }

        protected virtual void Edit()
        { throw (new CommonException("Метод не реализован")); }

        #endregion




        #region Add...

        private void cmdAdd_Click(object sender, EventArgs e)
        {
            Add();
        }


        protected virtual void Add()
        {throw (new CommonException("Метод не реализован")); }

        #endregion




        #region Ready...

        protected void FireEventReady(EventArgs pEventArgs)
        {
            try
            {
                if (EventReady != null) EventReady(this, pEventArgs);

            }

            catch (Exception e) { throw e; }
            finally { }
        }


        protected virtual void Ready()
        {
            try
            {
                FireEventReady(EventArgs.Empty);
                this.Close();
            }

            catch (Exception e) { MessageBox.Show(e.Message); }
            finally { }
        }


        private void cmdReady_Click(object sender, EventArgs e)
        {
            Ready();

        }

        #endregion




 



        #region SetCurItem...

        private void dgvMain_RowEnter(object sender, DataGridViewCellEventArgs e)
        {RowEnter(sender, e); }


        private void RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {

                if (mvarFlgStateLoadForm == false) 
                {
                   int lId;
                   DataGridViewRow lRowCur;
                   lRowCur = ((DataGridView)sender).Rows[e.RowIndex];
                   lId = (int)lRowCur.Cells["Id"].Value;
                   SetCurItem(lId);
                }

            }

            catch (Exception e1) { throw e1; }
            finally { }
        }


        protected virtual void SetCurItem(int pCurItem)
        {
            try { throw (new CommonException("Метод не реализован")); }
            catch (Exception e) { throw e; }
            finally { }
        }

        #endregion

 


        private void TFrmRegDirBase_Shown(object sender, EventArgs e)
        {
            mvarFlgStateLoadForm = false;
        }



        #region Cancel...

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }

 
        private void Cancel()
        {
            this.Close();

        }

        #endregion







 



 

 







    


















    }
}
